<?php

/**
 * 调用WEB退款接口(通联收银台)
 * 开发对外第三方下游渠道退款操作
 * @author chenshubo
 */
namespace App\Service\OrderService\OrderInterfaceService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;

class OrderWebCashRefund extends BaseService
{
    //退款客户端
    public $payClient = [
        3 => 'App\\Service\\VendorClient\\AlinpayApi\\AlinpayApiClient',//通联支付客户端
    ];
    
    /**
     * 进行退款操作
     * @param array $param
     */
    public function index( $param = [] ) 
    {
        $requestData = $param['requestData'];
        $binfo       = $param['binfo'];
        if( empty($requestData['orderSn']) ) {
            return Normal::returnCode(Normal::FAIL,"orderSn不能为空");
        }
        
        if( empty($requestData['orderRefundMoney']) ) {
            return Normal::returnCode(Normal::FAIL,"orderRefundMoney不能为空");
        }
        
        $notifyUrl      = $requestData['notifyUrl']??'';
        $frontUrl       = $requestData['frontUrl']??'';
        $orderSn        = checkFields($requestData['orderSn']);
        $refundMoney    = checkFields($requestData['orderRefundMoney']);
        if( $orderSn != $requestData['orderSn'] ) {
            return Normal::returnCode(Normal::FAIL,"orderSn订单号不能包含特殊字符");
        }
        
        //获取当前订单信息
        $bid = $binfo['bid'];
        $orderInfo = OrderSupplier::instance()
        ->select([
            'id',
            'order_status',
            'order_sn',
            'supplier_dsn',
            'real_total_money',
            'pay_way',
            'pay_time'
        ])
        ->where('bid',$bid)
        ->where('order_sn',$orderSn)
        ->where('order_type',0)
        ->where('after_sale_status',1)
        ->where('order_refund_status',0)
        ->get()
        ->toArray();
        
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不满足待退款条件");
        }
        
        //待退款总金额
        $real_total_money = 0;
        foreach ($orderInfo as $item ) {
            $real_total_money = bcadd((string)$real_total_money,(string)$item['real_total_money'],2);
        }
        
        //退款金额 是否大于订单金额
        if( bccomp($real_total_money, $refundMoney,2) < 0  ) {
            return Normal::returnCode(Normal::FAIL,"当前退款金额超出实际应退金额，请核对！");
        }
        
        $firtOrderInfo = current($orderInfo);
        //订单已发货，售后退款请联系客服协商处理！
        if( $firtOrderInfo['order_status'] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"订单已发货，售后退款请联系客服协商处理！");
        }
        
        $payWay = $firtOrderInfo['pay_way'];
        if ( !isset($this->payClient[$payWay]) ) {
            return Normal::returnCode(Normal::FAIL,"payWay不存在");
        }
        
        $class = $this->payClient[$payWay];
        $method = 'OrderRefund';
        if( !method_exists($class, $method) ) {
            return Normal::returnCode(Normal::FAIL,"当前支付类{$class}方法{$method}不存在");
        }
        
        OrderSupplier::instance()->startTrans();
        //退款成功
        $orderData = [
            'order_refund_status'       => 2,
            'order_refund_apply_money'  => $refundMoney,
            'order_refund_apply_time'   => time(),
        ];
        $res = OrderSupplier::instance()->where('bid',$bid)->where('order_sn',$orderSn)->where('after_sale_status',1)->where('order_refund_status',0)->update($orderData);
        if( !$res ) {
            OrderSupplier::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"申请退款失败，请稍后重试");
        }
        
        $data = [
            'order_sn'  => $orderSn,
            'money'     => $refundMoney,
            'pay_time'  => $firtOrderInfo['pay_time']
        ];
        $res = $class::instance()->{$method}($data);
        if( $res['code'] != Normal::SUC ) {
            OrderSupplier::instance()->rollback();
            return $res;
        }
        
        //通联退款同步接口
        if( $payWay == 3 ) {
            //退款成功
            $orderData = [
                'order_refund_status'       => 1,
                'order_refund_real_money'   => $refundMoney,
                'order_refund_real_time'    => time(),
                'order_refund_remark'       => '退款操作成功'
            ];
            OrderSupplier::instance()->where('bid',$bid)->where('order_sn',$orderSn)->where('after_sale_status',1)->where('order_refund_status',2)->update($orderData);
        }
        
        OrderSupplier::instance()->commit();
        return Normal::returnCode(Normal::SUC,"退款操作申请成功，请等待退款处理！");
    }
}